/**
 *
 */
package antsclub.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import antsclub.common.util.ConstUtil;
import antsclub.common.util.DateUtil;
import antsclub.model.Gym;
import antsclub.model.GymType;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;

/**
 * @author Kyle Yuan
 *
 */
public class GymController extends Controller {
    public void index() {
        String typeId = "258e9b10-2a86-48ef-8fad-624568c1cb45";
        String pageNumber = getPara(0);
        String sql = "select * from gym where typeId = ? order by seq limit ? , 9";
        List<Gym> gymList = Gym.dao.find(sql,typeId,(Integer.parseInt(pageNumber)-1)*9);
       
//        List<Gym> gymList = Gym.dao.find("select * from gym " +
//                " where typeId=?"+
//                " order by seq limit "+(Integer.parseInt(pageNumber)-1)*9+",9",typeId);
        JSONObject json = new JSONObject();
        json.put("gymList", gymList);
        renderJson(JsonKit.toJson(json));
    }
   
    public void save(){
        try{
            Gym gym = getModel(Gym.class);
            gym.set("id", UUID.randomUUID().toString());
            gym.set("typeId", "258e9b10-2a86-48ef-8fad-624568c1cb45");
            String currentTime = DateUtil.formatDate(new Date(),ConstUtil.YMD_DASH_WITH_FULL_TIME);
            gym.set("createTime", currentTime);
            gym.set("updateTime", currentTime);
            boolean b = gym.save();
            if(b){
                setAttr("msg", ConstUtil.MESSAGE_SAVE_SUCCESS);
                render(ConstUtil.URL_GYM_LIST_PAGE);
            }else{
                setAttr("msg", ConstUtil.MESSAGE_SAVE_FAILD);
                render(ConstUtil.URL_GYM_ADD_PAGE);
            }
        }catch(Exception e){
            setAttr("msg", e);
            render(ConstUtil.URL_GYM_ADD_PAGE);
        }
    }
   
    public void saveType(){
        try{
            GymType gymType = getModel(GymType.class);
            gymType.set("id", UUID.randomUUID().toString());
            String currentTime = DateUtil.formatDate(new Date(),ConstUtil.YMD_DASH_WITH_FULL_TIME);
            gymType.set("createTime", currentTime);
            gymType.set("updateTime", currentTime);
            boolean b = gymType.save();
            if(b){
                setAttr("msg", ConstUtil.MESSAGE_SAVE_SUCCESS);
                render(ConstUtil.URL_GYM_LIST_PAGE);
            }else{
                setAttr("msg", ConstUtil.MESSAGE_SAVE_FAILD);
                render(ConstUtil.URL_GYM_TYPE_ADD_PAGE);
            }
        }catch(Exception e){
            setAttr("msg", e);
            render(ConstUtil.URL_GYM_TYPE_ADD_PAGE);
        }
    }
}